package middleware

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"longmen/server/config/global"
)

func TokenValid(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	var (
		keyValue         []string
		appId, appSecret string
		contextMap, ok   = metadata.FromIncomingContext(ctx)
	)

	if !ok {
		return nil, status.Errorf(codes.Unauthenticated, "miss meta data")
	}

	if keyValue, ok = contextMap["app_id"]; ok {
		appId = keyValue[0]
	}
	if keyValue, ok = contextMap["app_secret"]; ok {
		appSecret = keyValue[0]
	}
	if appId != global.Config.GetString("grpc.appid") ||
		appSecret != global.Config.GetString("grpc.secret") {
		return nil, status.Errorf(codes.Unauthenticated, "miss token")
	}
	// Continue execution of handler after ensuring a valid token.
	return handler(ctx, req)
}
